package com.ssy.lingxi.purchase.entity.converter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.purchase.api.dto.response.online.CountryArea;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.ArrayList;
import java.util.List;

/**
* 将自定义的报名地址信息Entity，与表中的Jsonb字段进行转换
* @author lxc
* @date 2022/4/6
*/
@Converter(autoApply = true)
public class JpaJsonToCountryAreaConverter implements AttributeConverter<CountryArea, String> {
    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(CountryArea attribute) {
        try {
            return OBJECT_MAPPER.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"报名地址转换Json错误");
        }
    }

    @Override
    public CountryArea convertToEntityAttribute(String dbData) {
        try {
            if(dbData == null) {
                return new CountryArea();
            }

            return OBJECT_MAPPER.readValue(dbData, new TypeReference<CountryArea>() {});
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"数据库json字段转换报名地址实体错误");
        }
    }
}
